/**
 * config:
 * sliderId 轮播图容器id
 * imgList 轮播图列表
 * autoplay 是否自动播放
 * aniTIme  动画时长
 * intervalTime  自动播放轮播图切换时间
 */
function Slider(config) {
  if (!config.sliderId) {
    throw new Error("轮播容器id不能为空");
  }

  this.imgList = config.imgList || [];

  if (this.imgList.length === 0) {
    throw new Error("轮播列表不能为空");
  }

  // 轮播图片父容器
  this.sliderBoxDom = null;
  // 向前翻按钮
  this.prevBtnDom = null;
  // 向后翻按钮
  this.nextBtnDom = null;
  // 轮播分页容器
  this.sliderSpotDom = null;
  // 自动播放定时器
  this.timer = null;

  this.aniTIme = config.aniTIme || 1000;
  this.intervalTime = config.intervalTime + this.aniTIme || 2000;
  // 当前播放的图片索引
  this.playIndex = 0;

  // 轮播外层容器
  this.sliderContainerDom = document.getElementById(config.sliderId);

  // 轮播图片容器每次的移动的宽度
  this.moveWidth = this.sliderContainerDom.offsetWidth;

  // 节流要用到的时间对比单位
  this.prev = Date.now();

  // 自动播放设置
  this.autoplay = config.autoplay;
}

Slider.prototype = {
  init() {
    this.createSliderDom();
    if (this.autoplay) {
      this.timer = setInterval(this.toPrev.bind(this, this.aniTIme), this.intervalTime);
    }

    // 上一张，下一张，分页器绑定点击事件
    this.bindSliderEvent();
  },
  // 动态创建轮播图节点内容
  createSliderDom() {
    // 创建轮播图片容器
    this.sliderBoxDom = document.createElement("ul");
    this.sliderBoxDom.className = "slider-box";

    // 将第一张图片添加到最后，将最后一张图片添加到最前，实现无缝轮播
    let realImgList = [this.imgList[this.imgList.length - 1], ...this.imgList, this.imgList[0]];

    // 添加轮播图片
    this.sliderBoxDom.innerHTML = realImgList
      .map((item, index) => {
        let dom = [
          `<li  class="slider-item">`,
          `<a href="${item.jumpUrl}"><img src="${item.imgPath}" alt=""></a>`,
          "</li>",
        ];
        return dom.join("");
      })
      .join("");

    // 初始偏移位置
    this.sliderBoxDom.style.transform = `translateX(${-this.moveWidth}px)`;

    this.sliderContainerDom.appendChild(this.sliderBoxDom);

    // 创建切换轮播图的分页器按钮容器
    this.sliderSpotDom = document.createElement("ul");
    this.sliderSpotDom.className = "slider-spot";
    // 分页器
    this.sliderSpotDom.innerHTML = this.imgList
      .map((item, index) => {
        return `<li class="spot-item ${index === 0 ? "active" : ""}"  data-index=${index}></li>`;
      })
      .join("");
    this.sliderContainerDom.appendChild(this.sliderSpotDom);

    // 创建向前翻按钮
    this.prevBtnDom = document.createElement("img");
    this.prevBtnDom.className = "slider-btn prev";
    this.prevBtnDom.src = "./imgs/left.png";

    // 创建向后翻按钮
    this.nextBtnDom = document.createElement("img");
    this.nextBtnDom.className = "slider-btn next";
    this.nextBtnDom.src = "./imgs/right.png";

    // 如果只有一张图片，则隐藏向前和向后翻按钮
    if (this.imgList.length === 1) {
      this.prevBtnDom.style.display = "none";
      this.nextBtnDom.style.display = "none";
    }

    this.sliderContainerDom.appendChild(this.prevBtnDom);
    this.sliderContainerDom.appendChild(this.nextBtnDom);
  },
  // 绑定轮播事件
  bindSliderEvent() {
    // ==========================PC端事件绑定===================
    // 向前翻事件绑定
    this.prevBtnDom.addEventListener("click", () => {
      this.throttle(this.toPrev, 300, 300);
    });

    // 鼠标悬停在向前翻按钮时,停止自动播放
    this.prevBtnDom.addEventListener("mouseover", () => {
      clearInterval(this.timer);
    });
    // 鼠标离开在向前翻按钮时,恢复自动播放
    this.prevBtnDom.addEventListener("mouseout", () => {
      this.timer = setInterval(this.toNext.bind(this, this.aniTIme), this.intervalTime);
    });

    // 向后翻事件绑定
    this.nextBtnDom.addEventListener("click", () => {
      this.throttle(this.toNext, 300, 300);
    });

    this.nextBtnDom.addEventListener("mouseover", () => {
      clearInterval(this.timer);
    });
    this.nextBtnDom.addEventListener("mouseout", () => {
      this.timer = setInterval(this.toNext.bind(this, this.aniTIme), this.intervalTime);
    });

    this.sliderSpotDom.addEventListener("mouseover", () => {
      clearInterval(this.timer);
    });
    this.sliderSpotDom.addEventListener("mouseout", () => {
      this.timer = setInterval(this.toNext.bind(this, this.aniTIme), this.intervalTime);
    });

    // 分页器按钮事件绑定
    this.sliderSpotDom.addEventListener("click", (e) => {
      if (e.target.tagName.toLowerCase() === "li") {
        this.playIndex = parseInt(e.target.dataset.index);
        this.setActiveSpot();
        this.sliderBoxDom.style.transition = `.8s  ease-in-out`;
        this.sliderBoxDom.style.transform = `translateX(${-(this.playIndex + 1) * this.moveWidth}px)`;
      }
    });

    // 移动端事件绑定
    this.sliderBoxDom.addEventListener("touchstart", (e) => {
      clearInterval(this.timer);
      this.startX = e.changedTouches[0].clientX;
      this.startY = e.changedTouches[0].clientY;
    });
    this.sliderBoxDom.addEventListener("touchmove", (e) => {
      clearInterval(this.timer);
      this.endX = e.changedTouches[0].clientX;
      this.endY = e.changedTouches[0].clientY;
    });
    this.sliderBoxDom.addEventListener("touchend", (e) => {
      if (!this.sliderBoxDom.style.transition) {
        this.sliderBoxDom.style.transition = ` ${this.aniTIme / 1000}s ease-in-out`;
      }
      let angle = this.angle({ X: this.startX, Y: this.startY }, { X: this.endX, Y: this.endY });
      if (Math.abs(angle) > 30) return;

      // 判断滑动方向
      if (this.endX > this.startX) {
        // 右滑
        this.toNext();
      } else {
        // 左滑
        this.toPrev();
      }
      this.timer = setInterval(this.toNext.bind(this, this.aniTIme), this.intervalTime);
    });
  },
  // 向前翻
  toPrev(aniTIme) {
    if (this.imgList.length === 1) return;

    this.sliderBoxDom.style.transition = `${aniTIme / 1000}s ease-in-out`;
    this.sliderBoxDom.style.transform = `translateX(${-this.playIndex * this.moveWidth}px)`;
    if (this.playIndex === 0) {
      this.playIndex = this.imgList.length - 1;
      setTimeout(() => {
        this.sliderBoxDom.style.transitionProperty = "none";
        this.sliderBoxDom.style.transform = `translateX(${-this.imgList.length * this.moveWidth}px)`;
      }, aniTIme);
    } else {
      this.playIndex--;
    }
    this.setActiveSpot();
  },
  // 向后翻
  toNext(aniTIme) {
    if (this.imgList.length === 1) return;
    this.playIndex++;

    this.sliderBoxDom.style.transition = `${aniTIme / 1000}s ease-in-out`;
    this.sliderBoxDom.style.transform = `translateX(${-(this.playIndex + 1) * this.moveWidth}px)`;

    if (this.playIndex === this.imgList.length) {
      this.playIndex = 0;
      setTimeout(() => {
        this.sliderBoxDom.style.transitionProperty = "none";
        this.sliderBoxDom.style.transform = `translateX(${-this.moveWidth}px`;
      }, aniTIme);
    }
    this.setActiveSpot();
  },
  // 设置当前分页按钮为高亮选中状态
  setActiveSpot() {
    this.sliderSpotDom.childNodes.forEach((item, index) => {
      if (index === Math.abs(this.playIndex)) {
        item.classList.add("active");
      } else {
        item.classList.remove("active");
      }
    });
  },

  // 节流
  throttle(handle, delay, val) {
    let now = Date.now();
    if (now - this.prev >= delay) {
      handle.call(this, val);
      this.prev = Date.now();
    }
  },
  /**
   * 计算滑动角度
   * @param {} start 起点坐标
   * @param {} end 终点坐标
   */
  angle(start, end) {
    let x = end.X - start.X,
      y = end.Y - start.Y;
    //返回角度 /Math.atan()返回数字的反正切值
    return (360 * Math.atan(y / x)) / (2 * Math.PI);
  },
};
